import { onMounted, reactive } from "vue";
import LocalCache from "@/utils/storage";
import wx from "weixin-js-sdk";
import { useAuthStore } from "@/stores/auth";
import { storeToRefs } from "pinia";
const authStore = useAuthStore();
const { token, tenant } = storeToRefs(authStore);
export function useUrlParams() {
  const data = reactive({
    token: "",
    tenant: "",
  });

  function parseFragmentParams(url: string) {
    const fragment = url.split("#")[1]; // 获取#后面的部分
    if (!fragment) {
      return {}; // 如果没有片段，返回一个空对象
    }
    const params = {};
    const pairs = fragment?.split("?")[1]?.split("&") || []; // 假设?后面紧跟参数
    pairs.forEach((pair) => {
      const [key, value] = pair.split("=");
      params[key] = value || ""; // 将参数和值添加到对象中
    });
    return params;
  }

  onMounted(() => {
    let temp = window.location.href;
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) === "micromessenger") {
      //ios的ua中无miniProgram，但都有MicroMessenger（表示是微信浏览器）
      wx.miniProgram.getEnv((res) => {
        if (res.miniprogram) {
          // 小程序中打开h5跳转小程序页面
          console.log("在微信里");
        } else {
          // 非小程序
        }
      });
    } else {
      console.log("不在微信里");
      console.log(window.location.href);
      const fragmentParams = parseFragmentParams(temp);
      data.token = fragmentParams.token;
      data.tenant = fragmentParams.tenant;

      if (data.token && data.tenant) {
        useAuthStore().setTenant(data.tenant);
        useAuthStore().setToken(data.token);
        LocalCache.set("token", data.token);
        LocalCache.set("tenant", data.tenant);
      }
      console.log(token.value, "23");
      console.log(tenant.value, "23");
    }
  });

  return {
    data,
  };
}
